package com.example.mydemo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.pad.filelibrary.utils.FileUtils2;
import com.tal.pad.eye_protection.AwConDetectApi;
import com.tal.pad.eye_protection.interfaces.NoPersonStatusCallback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
    private static final int PERMISSION_REQUEST_CODE = 1;


    private Camera camera;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;

    private boolean isStar = false;
    private String sessionId = "a12ssss";

    private Button button;
    private Button button1;
    private Button button2;


    private int id1=0;
    private Handler handler;
    private Thread thread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        surfaceView = findViewById(R.id.surfaceView);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        button = findViewById(R.id.button);
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isStar = true;
                if (thread!=null && thread.getState() == Thread.State.NEW){
                    thread.start();
                }

            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isStar = false;
                try {
                    thread.interrupt();
                } catch (Exception e) {
                   e.printStackTrace();
                }

            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AwConDetectApi.getInstance().getNoPersonStatus(new NoPersonStatusCallback() {
                    @Override
                    public void onNoPersonStatus(int status) {
                        Log.e("++", "onNoPersonStatus: "+status );
                    }
                });
            }
        });
        // 检查并请求权限
        checkAndRequestPermissions();

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 1) {
                    FileUtils2.getInstance().dirToZip( sessionId,MainActivity.this);
                }else if (msg.what == 2) {
                    id1++;
                    sessionId="a12ssss"+id1;

                }
                return true;
            }
        });

        // 启动子线程
        thread= new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                 A();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

    }
    public void A () throws InterruptedException {
        // 模拟耗时操作
        Thread.sleep(5000);
        // 创建消息对象
        Message message = Message.obtain();
        message.what = 1;

        // 发送消息到 Handler
        handler.sendMessage(message);
        Thread.sleep(30000);
        Message message2 = Message.obtain();
        message2.what = 2;
        handler.sendMessage(message2);
        A();
    }
    private void checkAndRequestPermissions() {
        List<String> permissionsToRequest = new ArrayList<>();


        // 检查相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.CAMERA);
        }


        // 如果有需要请求的权限，则发起请求
        if (!permissionsToRequest.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    permissionsToRequest.toArray(new String[0]),
                    PERMISSION_REQUEST_CODE);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }
            if (allPermissionsGranted) {
                Toast.makeText(this, "所有权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "部分权限未授予", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private int findFrontFacingCamera() {
        int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                return i;
            }
        }
        return -1;
    }
    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        try {

                // 查找前置摄像头
                int cameraId = findFrontFacingCamera();
                if (cameraId >= 0) {
                    // 打开前置摄像头
                    camera = Camera.open(cameraId);
                    camera.setPreviewDisplay(holder);
                }


            camera.setPreviewCallback(new Camera.PreviewCallback() {
                @Override
                public void onPreviewFrame(byte[] data, Camera camera) {
                    // 获取相机参数
                    Camera.Parameters parameters = camera.getParameters();
                    int width = parameters.getPreviewSize().width;
                    int height = parameters.getPreviewSize().height;
                    AwConDetectApi.getInstance().detectFrame(data,width,height,0,0,0,sessionId);

                    if (isStar) {
                        FileUtils2.getInstance().processFrame(data, width, height, ImageFormat.NV21, sessionId);
//                        FileUtils2.processFrame(data, width, height, ImageFormat.NV21, sessionId);
                    }


                }
            });
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        if (surfaceHolder.getSurface() == null) {
            return;
        }
        try {
            camera.stopPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        if (camera != null) {
            camera.setPreviewCallback(null);
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

}